using AutoMapper;
using Microsoft.EntityFrameworkCore;
using ShopForWeb.Dto.ViewModels;
using ShopForWeb.Models;

namespace ShopForWeb.Service;

public class ShopCartService
{
  private ShopDbContext _context;
  private IMapper _map;
  public ShopCartService(ShopDbContext context, IMapper map)
  {
    _context = context;
    _map = map;
  }
  //添加
  public async Task<int> AddNewAsync(ShopCartViewModel scvm)
  {
    var temp = await _context.ShopCarts
                       .Where(sc => sc.UserID == scvm.UserID && sc.CommodityID == scvm.CommodityID)
                       .FirstOrDefaultAsync();
    if (temp != null)
    {
      return 0;
    }
    ShopCart sc = _map.Map<ShopCart>(scvm);
    _context.Entry(sc).State = EntityState.Added;
    return await _context.SaveChangesAsync();
  }
  public async Task<List<ShopCartViewModel>> GetByUserIDAsync(int userid)
  {
    var scs = await _context.ShopCarts
                      .Include(sc => sc.Commodity)
                      .Where(sc => sc.UserID == userid)
                      .AsNoTracking()
                      .ToListAsync();
    return _map.Map<List<ShopCartViewModel>>(scs);
  }
  //删除
  public async Task<int> RemoveAsync(int userID, int commodityID)
  {
    ShopCart sc = new ShopCart()
    {
      UserID = userID,
      CommodityID = commodityID
    };
    _context.ShopCarts.Remove(sc);
    return await _context.SaveChangesAsync();
  }
}
